// pages/pay/ChoosePay2.js
let network = null;
let utils = null;
let api = null;
let Zan = require('../../dist/index');
const app = getApp();

Page(Object.assign({}, Zan.TopTips, Zan.Toast, {

  /**
   * 页面的初始数据
   */
  data: {
    isWxPay: true,
    order: null,
    formId: '',
    userInfo: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    network = new app.NetWorkUtils();
    utils = new app.Utils();
    api = new app.Api();

    this.setData({
      order: JSON.parse(options.order),
      store: JSON.parse(decodeURIComponent(options.store)),
      userInfo: app.globalData.userInfo
    })
    console.log(app.globalData.userInfo);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // },
  selectTap: function () {
    this.setData({
      isWxPay: !this.data.isWxPay
    })
  },

  formIdSubmitPay: function (e) {
    this.setData({
      formId: e.detail.formId
    })
    if (this.data.isWxPay) {
      network._post_json(this, api.offlineWechat, { id: this.data.order.orderId }, wxPaySuccess);
    } else {
      network._post_json(this, api.offlineBalance, { formId: this.data.formId, id: this.data.order.orderId }, balanceSuccess);
    }
  },
  Refresh(){
    wx.navigateBack({
      delta: 2
    })
  }
}))

var wxPaySuccess = function (that, res) {
  var predata = res.data.data;
  wx.requestPayment({

    timeStamp: predata.timeStamp.toString(),
    nonceStr: predata.nonceStr,
    package: predata.package,
    signType: predata.signType,
    paySign: predata.paySign,
    success: function (res) {
      if (res.data.message == "支付成功") {
        that.showZanToast('支付成功');
        WxNotificationCenter.postNotificationName('couponRefreshNotification');
        var timer = setTimeout(that.Refresh, 1500);
        
      }
    },
    fail: function (res) {

    },
  });
}

var balanceSuccess = function (that, res) {
  if (res.data.message == "支付成功") {
    that.showZanToast('支付成功');
    WxNotificationCenter.postNotificationName('couponRefreshNotification');
    var timer = setTimeout(that.Refresh, 1500);
  }
}
